import type { PositionDetail, PositionDetailRequest, PositionItem, PositionListQuery } from "@/pages/internship/position-student/apis/type"
import type { OptionItem } from "@/pages/internship/position/apis/type"
import { ElMessage } from "element-plus"
import { reactive, ref } from "vue"
import { createPositionApplicationApi, getPositionDetailApi, getStudentPositionListApi } from "@/pages/internship/position-student/apis"
import { getPositionOptionsApi } from "@/pages/internship/position/apis/index"
import { pinia } from "@/pinia"
import { useUserStore } from "@/pinia/stores/user"

export const usePositionStudentStore = defineStore("positionStudent", () => {
  // 列表与分页状态
  const loading = ref(false)
  const list = ref<PositionItem[]>([])
  const total = ref(0)
  const query = reactive<PositionListQuery>({
    keyword: "",
    workType: undefined,
    workCity: undefined,
    period: undefined,
    salary: undefined,
    positionType: undefined,
    isFavorite: undefined,
    ignoreStatus: false,
    page: 1,
    size: 5
  })
  const positionDetail = ref<PositionDetail | null>(null)
  const detailLoading = ref(false)

  // 选项数据 - 改为ref类型以便动态更新
  const workTypeOptions = ref<OptionItem[]>([])
  const workCityOptions = ref<OptionItem[]>([])
  const periodOptions = ref<OptionItem[]>([])
  const salaryOptions = ref<OptionItem[]>([])
  const positionTypeOptions = ref<OptionItem[]>([])

  // 获取选项数据的方法
  const fetchOptions = async () => {
    try {
      const response = await getPositionOptionsApi()
      if (response && response.data) {
        const optionsData = response.data

        // 设置各选项数据，确保类型安全
        workTypeOptions.value = optionsData.workTypeOptions || []
        workCityOptions.value = optionsData.workCityOptions || []
        periodOptions.value = optionsData.periodOptions || []
        salaryOptions.value = optionsData.salaryOptions || []
        positionTypeOptions.value = optionsData.positionTypeOptions || []
      }
    } catch (error) {
      console.error("获取选项数据失败:", error)
      // 错误时使用默认数据作为备选
      applyDefaultOptions()
    }
  }

  // 应用默认选项数据
  const applyDefaultOptions = () => {
    workTypeOptions.value = [
      { value: 14, label: "线下实习" },
      { value: 15, label: "线上实习" },
      { value: 16, label: "混合模式" }
    ]
    workCityOptions.value = [
      { value: 24, label: "上海市" },
      { value: 25, label: "广东省" },
      { value: 26, label: "江苏省" },
      { value: 27, label: "浙江省" },
      { value: 28, label: "北京市" }
    ]
    periodOptions.value = [
      { value: 9, label: "1个月" },
      { value: 10, label: "3个月" },
      { value: 11, label: "6个月" },
      { value: 12, label: "6个月以上" }
    ]
    salaryOptions.value = [
      { value: 18, label: "无" },
      { value: 19, label: "3000元/月以下" },
      { value: 20, label: "3000-4000元/月" },
      { value: 21, label: "4000-5000元/月" },
      { value: 22, label: "5000元/月以上" }
    ]
    positionTypeOptions.value = [
      { value: 2, label: "Java开发实习生" },
      { value: 3, label: "前端开发实习生" },
      { value: 4, label: "UI设计实习生" },
      { value: 5, label: "产品经理实习生" },
      { value: 6, label: "人力资源实习生" },
      { value: 7, label: "市场推广实习生" }
    ]
    console.log("已应用默认选项数据")
  }

  // 拉取列表数据：reset=true 重置并从第1页开始；否则按页追加
  const fetchList = async (reset = false) => {
    if (loading.value) return
    loading.value = true

    if (reset) {
      list.value = []
      total.value = 0
      query.page = 1
    }

    try {
      let pageData: PositionItem[] = []
      let pageTotal = total.value

      const response = await getStudentPositionListApi(query)
      if (response && response.data && response.data.records) {
        pageData = response.data.records
        pageTotal = response.data.total
      }

      // 确保Vue正确追踪数组变化的方式更新列表
      if (reset) {
        // 重置模式：使用新数组完全替换
        list.value = [...pageData]
      } else {
        // 追加模式：使用splice确保响应式更新
        const startIndex = list.value.length
        list.value.splice(startIndex, 0, ...pageData)
      }
      total.value = pageTotal
    } catch {
      // 错误时使用空列表
      if (reset) {
        list.value = []
      }
      total.value = 0
    } finally {
      loading.value = false
    }
  }

  // 加载更多
  const loadMore = async () => {
    if (loading.value) return
    if (list.value.length >= total.value) return
    query.page += 1
    await fetchList(false)
  }

  // 重置筛选条件
  const resetFilters = () => {
    query.keyword = ""
    query.workType = undefined
    query.workCity = undefined
    query.period = undefined
    query.salary = undefined
    query.positionType = undefined
    fetchList(true)
  }

  // 获取职位详情
  const fetchPositionDetail = async (id: number) => {
    if (!id || typeof id !== "number") {
      console.warn("无效的职位ID:", id)
      return
    }

    detailLoading.value = true
    try {
      const userStore = useUserStore()
      const userId = userStore.userInfo?.userId

      const response = await getPositionDetailApi({
        positionId: id,
        userId: userId ?? 0
      })

      // 检查响应数据
      if (response && response.data) {
        positionDetail.value = response.data
      } else {
        positionDetail.value = null
        ElMessage.error("获取职位详情失败")
      }
    } catch (error) {
      console.error("获取职位详情失败:", error)
      positionDetail.value = null
      ElMessage.error("获取职位详情失败，请稍后重试")
    } finally {
      detailLoading.value = false
    }
  }

  // 申请职位
  const applyPosition = async (positionId: number) => {
    const body: PositionDetailRequest = { positionId, userId: 0 }
    try {
      await createPositionApplicationApi(body)
      return true
    } catch (error) {
      console.error("申请职位失败:", error)
      return false
    }
  }

  // 清除职位详情
  const clearPositionDetail = () => {
    positionDetail.value = null
  }

  // 初始化 - 加载选项数据
  applyDefaultOptions()

  return {
    // 状态
    loading,
    list,
    total,
    positionDetail,
    detailLoading,
    query,
    // 选项数据
    workTypeOptions,
    workCityOptions,
    periodOptions,
    salaryOptions,
    positionTypeOptions,
    // 方法
    fetchList,
    loadMore,
    resetFilters,
    applyPosition,
    fetchPositionDetail,
    clearPositionDetail,
    fetchOptions
  }
})

/**
 * @description 在 SPA 应用中可用于在 pinia 实例被激活前使用 store
 * @description 在 SSR 应用中可用于在 setup 外使用 store
 */
export function usePositionStudentStoreOutside() {
  return usePositionStudentStore(pinia)
}
